package com.gitee.fastmybatis.core.ext.code.util;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Velocity工具类,根据模板内容生成文件
 *
 * @author tanghc
 */
public class VelocityUtil {

    private VelocityUtil() {
        super();
    }

    static {
        Velocity.init();
    }

    private final static String LOG_TAG = "velocity_log";

    public static String generate(VelocityContext context, InputStream inputStream) {
        return generate(context, inputStream, StandardCharsets.UTF_8);
    }

    public static String generate(VelocityContext context, InputStream inputStream, Charset charset) {
        return generate(context, new InputStreamReader(inputStream, charset));
    }

    public static String generate(VelocityContext context, String template) {
        return generate(context, new StringReader(template));
    }

    public static String generate(VelocityContext context, Reader reader) {
        StringWriter writer = new StringWriter();
        Velocity.evaluate(context, writer, LOG_TAG, reader);
        try {
            return writer.toString();
        } finally {
            try {
                reader.close();
            } catch (Throwable e) {
                // ignore
            }
        }
    }
}
